<%@ page contentType="text/html;charset=UTF-8" %>
<!-- 管理后台，模板区域设计操作工具类 -->
<style>
.codeModule{z-index:900;border:2px dashed #999;}
</style>
<script src="${ctx}/common/plateform/plugins/dragsort/jquery.dragsort-0.5.2.min.js"></script>
<script>
var thisCtrObj = null;//当前操作区域
var objNameMap = {};//记录涉及表对象
var thisObjName = null;//记录当前操作对象
var checkedColumMap = {};//记录已选字段对象

$(function (){
	loadDataTempClick();
});
//注入模板双击事件
function loadDataTempClick(){
	
	$("[data-temp-code]").each(function(){
		var thisId = $(this).attr("id");
		if($("[id='"+thisId+"']").length>1){
			layer.alert("有元素id="+thisId+" 重复啦，请检查！");
		}
		$(this).addClass("temp-boxadmin");
		//setObjHeight(thisId);
		$(this).mouseover(function(){	//1、绑定鼠标移入事件
			$(this).addClass("fcur").addClass("codeModule");
			$(this).attr("title","双击可以进行设置");
		}).mouseout(function(){	//2、绑定鼠标移出事件
			$(this).removeClass("fcur").removeClass("codeModule");
			$(this).removeAttr("title");
		}).dblclick(function(){	//3、绑定鼠标双击事件
			var obj = $(this);
			thisCtrObj = obj;
			var codeStr = obj.attr("data-temp-code");
			var cols = strUtil.doNull(obj.attr("data-temp-cols"),6);
			if(!strUtil.isNull(codeStr)){
				var tmepType = obj.attr("data-temp-type");
				var codeArry = codeStr.split(",");
				var btnDivHtml = "";
				var objFirstNameKey = "";
				for(var i=0;i<codeArry.length;i++){
					var objectNameTmp = codeArry[i];
					objNameMap[objectNameTmp]=objectNameTmp;
					if(i==0){
						objFirstNameKey=objectNameTmp;
					}
					btnDivHtml+="<button obj-name=\""+objectNameTmp+"\" class=\"btn btn-default\" onclick=\"addTabObjColum('"+objectNameTmp+"');\" type=\"button\"><i class=\"fa fa-cog\"></i> "+objectNameTmp+"对象选择</button> ";
				}
				$("#modal-btn-div").html(btnDivHtml);
				$("#select_column_size").val(cols);
				$("#select_tempType").val(tmepType);
				$("#modal_colum_checkbox").modal("show");
				$("#tabs_checkboxed_colum_content").html("");
				
				getTabObjHistoryMap();//解析加载页面已经存在区域，转json格式map对象
				addTabObjColum(objFirstNameKey);//默认加载第一个表对象的字段
				
			}
		});	
	});
	
}
//设置元素高度
function setObjHeight(objId){
	var defHeight = "120";
	if($("#"+objId).height()>defHeight) {
		defHeight = $("#"+objId).height();
	}
	$("#"+objId).addClass("temp-boxadmin");
	//$("#"+objId).css("height",defHeight);
}

//获取页面已经存在的元素列
function getTabObjHistoryMap(){
	//2、获取页面已经存在的元素存储map，方便匹配 
	checkedColumMap = {};
	thisCtrObj.find("[data-temp-obj]").each(function(){
		var objStr = $(this).attr("data-temp-obj");
		var objName = objStr.split(".")[0];
		var colum = objStr.split(".")[1];
		var tagName = $(this)[0].tagName.toLowerCase();
		var title = $(this).attr("data-temp-title");
		var mapKey = objStr;
		if(tagName=="th"){
			title = $(this).text();
		}
		checkedColumMap[mapKey] = eval({"objName":objName,"colum":colum,"name":objStr,"title":title,"type":tagName});
	});
}

//点击button按钮加载指定表中的字段
function addTabObjColum(objName){
	thisObjName = objName;
	$("#modal_colum_checkbox_title").text(objName);

	//1、控制对象按钮选中状态
	$("#modal-btn-div").find("button").each(function(){
		if($(this).attr("obj-name")==objName){
			$(this).removeClass("btn-default").addClass("btn-danger");
		}else{
			$(this).removeClass("btn-danger").addClass("btn-default");
		}
	});
	
	var tabContentHtml="";
	var tabTobjContent = $("#tabs_checkbox_content");
	var index_load = layer.msg("数据正在加载中。。。", {shade: false,offset: '220px'});
	var sortDataParm = {"modelTypes":"s_sortInfo,s_metadata","sortInfo.sortId":"[metadata.sortId]","sortInfo.w_objName":objName,"metadata.w_ifAdd":"T"};
	$.get(common_list_url, sortDataParm,function(myData){
		layer.close(index_load);
		console.log(myData);
    	myData.objName=thisObjName;
    	myData.tempType = thisCtrObj.attr("data-temp-type");
    	tabTobjContent.html(baidu.template("tabs_checkbox_content-template",eval(myData)));
		
		//2、勾选已经存在的行数、复选框、值等
		tabTobjContent.find("tr").each(function(){
			var keyName = $(this).attr("name");
			if(checkedColumMap[keyName]){
				var objMap = checkedColumMap[keyName];
				$(this).addClass("bg-danger");
				$(this).find("td").find("input:checkbox").attr("checked",true);
				$(this).find("td").find("input[name='input_columTitle']").val(objMap.title);
				$(this).find("td").find("select").val(objMap.type);
			}
		});
   	},"json");
	
	//3、如果map不为空，则遍历checkedColumMap
	//alert(checkedColumMap+"=="+Object.keys(checkedColumMap).length);
	if(Object.keys(checkedColumMap).length>0){
		showColumCheckedData();
	}
}

//选中字段，设置背景颜色
function checkColumAttr(obj){
	var objTr = $(obj).parent().parent();
	var colum = $(obj).attr("colum");
	var mapKey = thisObjName+"."+colum;
	if(colum && $(obj).is(':checked')){
		var columTypeObj = objTr.find("select[name='select_columType']");
		var columTitle = objTr.find("input[name='input_columTitle']").val();
		if(strUtil.isNull(columTypeObj.val())){
			layer.tips("请先选择此字段显示类型！","#"+columTypeObj.attr("id"),{tips:3});
			$(obj).attr("checked", false);
			return;
		}
		objTr.addClass("bg-danger");
		checkedColumMap[mapKey] = eval({"objName":thisObjName,"colum":colum,"name":mapKey,"title":columTitle,"type":columTypeObj.val()});
	}else{
		objTr.removeClass("bg-danger");
		delete checkedColumMap[mapKey];//删除map元素
	}
	
	showColumCheckedData();
}
//选中colum赋值
function showColumCheckedData(){
	var contentColumDivId = "tabs_checkboxed_colum_content";
	var len  = Object.keys(checkedColumMap).length;
	if(len>0){
		closeDrag(contentColumDivId);
		var myData = {};
		myData.total=len;
		var rowsColum=new Array();
		var i = 0;
		for(var key in checkedColumMap){
			rowsColum[i]=checkedColumMap[key];
			i++;
		}
		var cols=strUtil.doNull($("#select_column_size").val(),6);
		var tempType=strUtil.doNull(thisCtrObj.attr("data-temp-type"),"form");
		myData.colSize=cols;
		myData.rows=rowsColum;
		//调用不同的template模板（form和table)
		var checkboxedHtml = baidu.template(tempType+"-preview-template",eval(myData));
		$("#"+contentColumDivId).html(checkboxedHtml);
		openDrag(contentColumDivId);
	}else{
		$("#"+contentColumDivId).html("");
	}
}
function changeColumSize(obj){
	showColumCheckedData();
}
//点击全部选择完成按钮后，开始保存到页面，写入文件中
function checkAllOkAndSave(){
	var len  = Object.keys(checkedColumMap).length;
	if(len<1){
		layer.alert("请至少选择一个对应字段！");
		return;
	}
	var perviewDivObj = $("#tabs_checkboxed_colum_content");
	var newContentText = "";
	
	//1、移除多余的预览样式、准备内容，填充到页面中
	var tempType = thisCtrObj.attr("data-temp-type");
	if(tempType=="form"){
		perviewDivObj.find(".drag-box").each(function(){
			$(this).removeClass("drag-box");
			$(this).removeAttr("title").removeAttr("style");
		});
		//获取最新html内容
		var checkedHtml = perviewDivObj.html();
		thisCtrObj.html(checkedHtml);
		
		newContentText += "<!--\n\t\t\t\t\t-->";
		var colsNew = $("#select_column_size").val();
		newContentText+="<div id=\""+thisCtrObj.attr("id")+"\" class=\"row\"  data-temp-code=\""+thisCtrObj.attr("data-temp-code")+"\" data-temp-type=\""+tempType+"\" data-temp-cols=\""+colsNew+"\">";
		newContentText+="\t\t"+thisCtrObj.html();
		newContentText+="<!--\n\t\t\t\t\t--></div>";
	}else if(tempType=="table"){
		thisCtrObj.html("");
		var thHtml = "";
		perviewDivObj.find(".drag-box").each(function(){
			$(this).removeClass("drag-box");
			$(this).removeAttr("title").removeAttr("style");
			var temObjName = $(this).attr("data-temp-obj");
			thHtml+="<!--\n\t\t\t\t\t\t\t\t--><th data-temp-obj=\""+temObjName+"\">"+$(this).text()+"</th>";
		});
		thisCtrObj.html(thHtml);
		thisCtrObj.removeClass("temp-boxadmin");
		
		newContentText += "<!--\t\t\t\t\t\t\t-->";
		newContentText+="<tr id=\""+thisCtrObj.attr("id")+"\" data-temp-code=\""+thisCtrObj.attr("data-temp-code")+"\" data-temp-type=\""+tempType+"\">";
		newContentText+=thisCtrObj.html();
		newContentText+="<!--\n\t\t\t\t\t\t\t--></tr>";
	}
	//alert(newContentText);
	$("#modal_colum_checkbox").modal("hide");
	
	//2、保存数据、写入后台
	var tempPath = window.location.pathname.replace("/portal/sendPage/","/")+".jsp";
	//alert(tempPath);
	var dataParam= {"flagType":"T","filePath":tempPath,"code":thisCtrObj.attr("id"),"newContent":newContentText};
	var index_submit = layer.confirm("您确定要保存设置吗？", {btn: ['Yes','No'],closeBtn: 0,offset: '220px'}
	, function(){
		layer.close(index_submit);
		var msgIndex = layer.msg("正在保存文件内容...");
		$.post(ctx+"/trans/template/setTemplateParams", dataParam,function(myData){
			window.location.reload();//刷新此页面
			layer.alert(myData.msg);
	   	}, "json");
	});
}

//选择器设置不同显示类型所要对接的数据。
function setColumParam(o,id){
	var selVal = $(o).val();
	if(strUtil.isNull(selVal) || selVal=="input"){
		$("#"+id).hide();
	}else if(selVal=="select"){
		$("#"+id).show();
	}
}
//切换选择
function chartDiv(obj){
	var iObj = $(obj).find("i");
	if(iObj.is(".fa-minus")){
		$("#tabs_checkbox_1").removeClass("col-lg-6").addClass("col-lg-1");
		$("#tabs_checkbox_2").removeClass("col-lg-6").addClass("col-lg-10");
	}else{
		$("#tabs_checkbox_1").removeClass("col-lg-1").addClass("col-lg-6");
		$("#tabs_checkbox_2").removeClass("col-lg-10").addClass("col-lg-6");
	}
}
//开启拖拽
function openDrag(id){
	   $("#"+id).dragsort({
	        dragSelector : ".drag-box",  //可以不用设置，他会根据$("#tableid")的类型来决定是tr还是li
	        dragEnd : function(){
	            //console.log($(this));  //拖动完成的回调函数，$(this)当前拖动对象
	        },
	        scrollSpeed:0,  //默认为5，数值越大拖动的速度越快，为0则拖动时页面不会滚动
	    });
}
//关闭拖拽
function closeDrag(id){
	$("#"+id).dragsort("destroy");
}
</script>

<div class="modal fade" id="modal_colum_checkbox" tabindex="-2" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="margin-top:10px; width:99%;">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
							×
						</button>
						<h4 class="modal-title">
							<font color="red">字段选择器[<span id="modal_colum_checkbox_title"></span>表]</font> 
						</h4>
					</div>
					<div class="modal-body box-body">
						<div class="col-lg-6" id="tabs_checkbox_1">
						 <div class="box box-info">
							<div class="box-header">
								<div class="pull-right">
					                <button type="button" class="btn btn-box-tool" id="btn-box-tool-coll" onclick="chartDiv(this)" data-widget="collapse"><i class="fa fa-minus"></i></button>
				                 </div>
							</div>
					        <div class="box-body">
								   <div class="form-group col-lg-12" id="modal-btn-div">
								   </div>
								   <table class="table table-bordered table-hover">
						                <thead>
											<tr>
												<th width="10%">字段代号</th>
												<th width="20%">字段名称</th>
												<th width="30%">对应显示名称</th>
												<th width="30%">显示类型</th>
												<th width="5%" class="text-center"><i class="fa fa-check"></i></th>
											</tr>
										</thead>
										<tbody id="tabs_checkbox_content">
										</tbody>	
					               </table>
					        </div>
				        </div>
				        </div>
				        <div class="col-lg-6" id="tabs_checkbox_2">
				         <div class="box box-danger">
							<div class="box-header ">
								<h3 class="box-title col-sm-3">内容预览</h5>
			                 	<div class="col-sm-6">
										<select id="select_column_size" onchange="changeColumSize(this)" class="form-control">
											<option value="12">每行显示1列-（col-lg-12）</option>
											<option value="6">每行显示2列-（col-lg-6）</option>
											<option value="4">每行显示3列-（col-lg-4）</option>
											<option value="3">每行显示4列-（col-lg-3）</option>
										</select>
			                 	</div>
			                 	<div class="col-sm-3 text-right">
			                 		<button type="button" class="btn btn-danger pull-left" onclick="checkAllOkAndSave();"> <i class="fa fa-check"></i> 选择完成 </button>
			                 	</div>
			                 </div>
							</div>
					        <div class="box-body">
								<div class="form-group" id="tabs_checkboxed_colum_content">
								</div>
					        </div>
				        	</div>
				        </div>
					</div>
				</div>
				<!-- /.modal-content -->
			</div>		
</div>

<script type="text/template" id="tabs_checkbox_content-template">
	<? for ( var i = 0; i < rows.length; i++) {?>
		<tr name="<?=objName+"."+rows[i].metadata.dataAttr?>">
           	<td><?=objName+"."+rows[i].metadata.dataAttr?></td>
 			<td><?=rows[i].metadata.dataFullName?></td>
 			<td><input name="input_columTitle" class="form-control clean" maxlength="20" value="<?=rows[i].metadata.dataFullName?>" /></td>
 			<td>
				<select <?if(tempType=='table'){?>disabled<?}?> onchange="setColumParam(this,'div_req_<?=rows[i].metadata.metadataId?>')" name="select_columType" class="form-control">
					<option value="input" <?if(tempType=='form'){?>selected="selected"<?}?>>input-输入框</option>
					<option value="select">select-下拉列表</option>
				   <!-- <option value="inputHidden" >input-隐藏域</option>
					<option value="radio">radio-单选</option>
					<option value="textarea">textarea-文本域</option>
					<option value="date">date-日期文本框</option>
				    <option value="uploadimg">uploadimg-上传图片</option>-->
					<?if(tempType=='table'){?><option value="th" selected="selected">table的表头th</option><?}?>
				</select>
				<div style="display:none;"" id="div_req_<?=rows[i].metadata.metadataId?>">
					<div class="input-group">
						<div class="input-group-addon red">请求地址：</div>
						<input name="input_reqUrl" class="form-control clean" maxlength="100" />
					</div>
					<div class="input-group">
						<div class="input-group-addon red">返回参数：</div>
						<input name="input_resColmun" class="form-control clean" maxlength="100"/>
					</div>
				</div>
			</td>
 			<td class="text-center"><input type="checkbox" name="<?=objName+"."+rows[i].metadata.dataAttr?>" colum="<?=rows[i].metadata.dataAttr?>" onclick="checkColumAttr(this)" /></td>
		</tr>
   <?}?>
</script>
<script type="text/template" id="form-preview-template">
	<? for ( var i = 0; i < rows.length; i++) {?>
		<div class="form-group col-lg-<?=colSize?> drag-box" title="拖拽排序" style="border:1px dashed #999;padding:5px 0 5px 0;">
			<label class="col-lg-5 control-label text-right" ><?=rows[i].title?>：</label>
			<div class="col-lg-7">
			<?if(rows[i].type=='input'){?>
				<input id="searchForm_<?=rows[i].objName?>_<?=rows[i].colum?>" name="<?=rows[i].name?>" class="form-control clean" maxlength="30"  data-temp-obj="<?=rows[i].name?>" data-temp-title="<?=rows[i].title?>"/>
			<?}else if(rows[i].type=='select'){?>
				<select id="searchForm_<?=rows[i].objName?>_<?=rows[i].colum?>" name="<?=rows[i].name?>" class="form-control clean" data-temp-obj="<?=rows[i].name?>" data-temp-title="<?=rows[i].title?>">
					<option value="">--请选择--</option>
				</select>
 			<?}?>
			</div>
		</div>
   <?}?>  		
</script>
<script type="text/template" id="table-preview-template">
	<? for ( var i = 0; i < rows.length; i++) {?>
		<div class="form-group col-lg-3 text-center drag-box" title="拖拽排序" data-temp-obj="<?=rows[i].name?>" style="border:1px dashed #999;padding:5px 0 5px 0;margin:5px 0 5px;">
			<?=rows[i].title?>
		</div>		
   <?}?>
</script>